package com.bruce.codeFactory.designMode.observer;

import java.util.List;

/**
 * @author luotuan
 * @Description
 * @create 2019-03-04 22:28
 **/
public class ThreadLifeCyleObserver implements LifeCycleListener {

    private final Object LOCK = new Object();

    public void concurrentQuery(List<String> ids){
        if(ids==null || ids.isEmpty()){
            return;
        }
        ids.stream().forEach(id->new Thread(new ObservableRunnable(this) {
            @Override
            public void run() {
                try {
                    notifyChange(new RunnableEvent(RunnableState.RUNNINT,Thread.currentThread(),null));
                    System.out.println("query for id: "+id);
                    Thread.sleep(1000);
                    notifyChange(new RunnableEvent(RunnableState.DONE,Thread.currentThread(),null));
                }catch (Exception e){
                    notifyChange(new RunnableEvent(RunnableState.ERROR,Thread.currentThread(),e));
                }
            }
        },id).start());
    }

    @Override
    public void onevent(ObservableRunnable.RunnableEvent event) {
        synchronized (LOCK){
            System.out.println("Current thread is ["+event.getThread().getName()+"] data change and state is ["+event.getState()+"]");
            if(event.getCause()!=null){
                System.out.println("Current thread is ["+event.getThread().getName()+"] filed");
                event.getCause().printStackTrace();
            }
        }
    }
}
